type ExpireData<T> = {
  expireTime: number;
  data: T;
};

export async function getCachedValue<T>(key: string, ttlMs: number, supplier: () => Promise<T>): Promise<T> {
  const save = async (): Promise<T> => {
    const data = await supplier();
    const toSave = JSON.stringify({ expireTime: Date.now() + ttlMs, data });
    localStorage.setItem(key, toSave);
    return data;
  };

  const str = localStorage.getItem(key);
  if (str === null) {
    return save();
  }

  const savedData: ExpireData<T> = JSON.parse(str);
  if (savedData.expireTime < Date.now()) {
    return save();
  }
  return savedData.data;
}
